import React, {Component} from "react";
import store from "./store";
import {
    getAddTodoItemAction,
    getDeleteTodoItemAction,
    getInputChangeAction,
    getTodoListAction
} from "./store/actionCreator";
import TodoListUI from './TodoListUI'
import './TodoList.css'
import './mock'

/**
 * 容器组件只关注业务逻辑，负责整个组件的功能逻辑
 */
class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = store.getState();
        this.handleStoreChange = this.handleStoreChange.bind(this);
        //订阅store，传入一个函数，这个函数会被自动的执行
        store.subscribe(this.handleStoreChange);
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleBtnClick = this.handleBtnClick.bind(this);
        this.handleDeleteItemClick = this.handleDeleteItemClick.bind(this)
    }

    render() {
        return (
            <TodoListUI
                inputValue={this.state.inputValue}
                list={this.state.list}
                handleInputChange={this.handleInputChange}
                handleBtnClick={this.handleBtnClick}
                handleDeleteItemClick={this.handleDeleteItemClick}
            />
        )
    }

    /**
     * 当你调用 store.dispatch(action) 将action发给store的时候
     * action就会被自动的执行
     */
    componentDidMount() {
        const action = getTodoListAction();
        store.dispatch(action)
    }

    handleInputChange(e) {
        const action = getInputChangeAction(e.target.value);
        store.dispatch(action)
    }

    handleStoreChange() {
        //当store里面的数据发生变化时，就使用store里面的数据替换到state里面的数据，这样就数据同步了
        this.setState(store.getState)
    }

    handleBtnClick() {
        if (store.getState().inputValue === '') {
            return;
        }
        const action = getAddTodoItemAction();

        store.dispatch(action)
    }

    handleDeleteItemClick(index) {
        const action = getDeleteTodoItemAction(index);
        store.dispatch(action)
    }
}

export default TodoList;